<script setup>
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, User, SwitchButton } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { logout as logoutApi } from '@/apis/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 计算属性
const isLoggedIn = computed(() => userStore.isLogin)
const username = computed(() => userStore.username)
const isAuthPage = computed(() => ['Login', 'Register'].includes(route.name))

// 处理登录/登出
const handleAuth = async () => {
  if (isLoggedIn.value) {
    // 已登录，显示登出确认
    try {
      await ElMessageBox.confirm('确定要登出吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      
      // 调用后端登出接口
      await logoutApi()
      
      // 清除前端用户信息
      userStore.logout()
      
      ElMessage.success('登出成功')
      
      // 跳转到首页
      if (router.currentRoute.value.name !== 'Home') {
        router.push('/')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('Logout error:', error)
        // 即使后端登出失败，也要清除前端状态
        userStore.logout()
        ElMessage.success('登出成功')
        router.push('/')
      }
    }
  } else {
    // 未登录，跳转到登录页
    router.push('/login')
  }
}

// 跳转到用户中心
const goToProfile = () => {
  router.push('/profile')
}
</script>

<template>
  <div id="air">
    <el-container>
      <!-- 只在非登录/注册页面显示导航 -->
      <el-header v-if="!isAuthPage">
        <el-menu class="el-menu-demo" mode="horizontal" :default-active="$route.path" router>
          <div class="el-menu-left">
            <el-menu-item index="/">
              Home
            </el-menu-item>
            <el-menu-item index="/file">
              File
            </el-menu-item>
          </div>
          <div class="el-menu-right">
            <template v-if="isLoggedIn">
              <el-dropdown>
                <span class="username-dropdown">
                  欢迎，{{ username }}
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="goToProfile">
                      <el-icon><User /></el-icon>
                      个人设置
                    </el-dropdown-item>
                    <el-dropdown-item divided @click="handleAuth">
                      <el-icon><SwitchButton /></el-icon>
                      登出
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
            <template v-else>
              <el-button type="primary" @click="handleAuth" class="login-btn">登录</el-button>
            </template>
          </div>
        </el-menu>
      </el-header>

      <el-main :class="{ 'auth-page': isAuthPage }">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </el-main>

      <!-- 只在非登录/注册页面显示页脚 -->
      <el-footer v-if="!isAuthPage">
        <a href="https://beian.miit.gov.cn/">京ICP备18028985号-2</a>
      </el-footer>
    </el-container>
  </div>
</template>



<style scoped>
#nav {
  font-family: Arial, Helvetica, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 40px;
}

.el-menu-demo {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.el-menu-left {
  display: flex;
  flex-direction: row;
}

.el-menu-right {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 0 20px;
}

.username-text {
  color: #606266;
  font-size: 14px;
}

.username-dropdown {
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.username-dropdown:hover {
  background-color: #f5f7fa;
}

.login-btn {
  margin-left: 10px;
}

.logout-btn {
  color: #f56c6c;
  font-size: 14px;
}

.logout-btn:hover {
  color: #f56c6c;
}

.flex-grow {
  flex-grow: 0.9;
}

.el-dialog {
  width: 120px;
}

.el-container {
  min-height: 100vh; /* 设置容器的最小高度为视口高度，确保容器至少占据整个屏幕高度 */
  display: flex;
  flex-direction: column;
}

.el-main {
  padding: 20px;
}

/* 登录/注册页面的主内容区域 */
.el-main.auth-page {
  padding: 0;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-footer {
  margin-top: auto; /* 将 footer 上边距设置为 auto，使其自动推到页面的最底部 */
  text-align: center; /* 居中文本内容 */
}
</style>
